from sqlalchemy.orm import Session
import models


def query_address(db: Session, code: str):
    address = []
    result = []
    # 通过code的长度判断查询的是哪一级的数据
    opt = len(code)
    if opt == 0:  # 查询所有省份数据
        address = db.query(models.ProvinceModel).all()
    if opt == 2:  # 通过省代码查询市
        address = db.query(models.CityModel).filter(
            models.CityModel.province_code == code).all()
    if opt == 4:  # 通过市代码查询县
        address = db.query(models.AreaModel).filter(
            models.AreaModel.city_code == code).all()
    if opt == 6:  # 通过县代码查询镇
        address = db.query(models.StreetModel).filter(
            models.StreetModel.area_code == code).all()
    if opt == 9:  # 通过镇代码查询村
        address = db.query(models.VillageModel).filter(
            models.VillageModel.street_code == code).all()
    for item in address:
        data = {}
        data['value'] = item.code
        data['text'] = item.name
        if opt != 9:
            data['children'] = []
        result.append(data)
    return result
